﻿@inject IUserBasketService basketService
@inject NavigationManager NavigationManager
@inject IWordpressService wpService
@inject IUserStatusService statusService
@inject IUserService userService
@inject IDialogService DialogService
@inject ILogger<SelectedImages> logger

@implements IDisposable
@inherits ImageGridBase

@if( gridImages == null )
{
    <div class="damselfly-selectedimages">
        <p>
            <em>Loading selection...</em>
        </p>
    </div>
}
else
{
    <div class="damselfly-selectedimages">
        @if( !gridImages.Any() )
        {
            <p>
                <em>No images in basket.</em>
            </p>
        }
        else
        {
            @for( var i = 0; i < gridImages.Count; i++ )
            {
                var info = new SelectionInfo { image = gridImages[i], index = i };
                <div class="damselfly-gridimage" @onclick="@(async e => { await ToggleSelected(e, info); })">
                    <GridImage CurrentImage=@info.image NavContext=@NavigationContexts.Basket DisplayFileName=@false GridImageSize=GridImageSize.Mini/>
                </div>
            }
        }
    </div>
}

<div class="damselfly-basketmanager">
    <BasketManager/>

    <div class="damselfly-imagebuttons">
        <AuthorizeView Policy="@PolicyDefinitions.s_IsEditor">
            <ToolbarButton IconStyle="fa-shopping-basket" OnClickCallback="@AddSelectedToBasket" Enabled="@ImagesSelected" title="Add Selection to Basket"/>
            <ToolbarButton IconStyle="fa-times-circle" OnClickCallback="@(() => basketService.Clear())" Enabled="@BasketHasImages" title="Clear Basket"/>
            <ToolbarButton IconStyle="fa-copy" OnClickCallback="@BasketCopy" Enabled="@BasketHasImages" title="Copy/Move to another basket"/>
            <ToolbarButton IconStyle="fa-edit" OnClickCallback="@OpenEditBasketDialog" title="Edit basket"/>
            <ToolbarButton IconStyle="fa-plus-circle" OnClickCallback="@OpenAddBasketDialog" title="Create a new basket"/>
        </AuthorizeView>
        <AuthorizeView Policy="@PolicyDefinitions.s_IsDownloader">
            <ToolbarButton IconStyle="fa-download" OnClickCallback="@ShowDownloads" Enabled="@BasketHasImages" title="Export/Download"/>
            <ToolbarButton StyleGroup="fab" IconStyle="fa-wordpress-simple" OnClickCallback="@UploadToWordPress" Enabled="@BasketHasImages" title="Upload to Wordpress"/>
        </AuthorizeView>

    </div>
</div>

@code {

    [Parameter] public bool ShowTags { get; set; } = true;

    public bool BasketHasImages => gridImages.Any();
    public bool ImagesSelected => selectionService.Selection.Any();

    private void UploadToWordPress()
    {
        var images = basketService.CurrentBasket.BasketEntries.Select(x => x.Image).ToList();
        _ = wpService.UploadImagesToWordpress(images);
    }

    private async Task BasketCopy()
    {
        var dialog = DialogService.Show<BasketMoveDialog>("Copy/Move to Basket");
        var result = await dialog.Result;
    }

    private async Task OpenAddBasketDialog()
    {
        var newBasket = new Basket { Name = "New Basket", UserId = userService.UserId };

        var parameters = new DialogParameters { { "basket", newBasket }, { "mode", "Add" } };
        var dialog = DialogService.Show<BasketDialog>("Add New Basket", parameters);
        var result = await dialog.Result;
    }

    private async Task OpenEditBasketDialog()
    {
        var parameters = new DialogParameters { { "basket", basketService.CurrentBasket }, { "mode", "Edit" } };
        var dialog = DialogService.Show<BasketDialog>("Edit Basket", parameters);
        var result = await dialog.Result;
    }

    async Task AddSelectedToBasket()
    {
        var selected = selectionService.Selection.ToList();
        await basketService.SetImageBasketState(true, selected.Select(x => x.ImageId).ToList());

        statusService.UpdateStatus($"{selected.Count()} images added to the basket");
    }

    private void ShowDownloads()
    {
        try
        {
            NavigationManager.NavigateTo("/export");
        }
        catch( Exception ex )
        {
            logger.LogError("Exception: " + ex.Message);
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if( firstRender )
        {
            basketService.OnBasketChanged += BasketImagesChanged;
            selectionService.OnSelectionChanged += SelectedImagesChanged;
            await LoadData();
        }
    }

    public void Dispose()
    {
        basketService.OnBasketChanged -= BasketImagesChanged;
        selectionService.OnSelectionChanged -= SelectedImagesChanged;
    }

    protected void SelectedImagesChanged()
    {
        StateHasChanged();
    }

    protected void BasketImagesChanged(BasketChanged change)
    {
        _ = LoadData();
    }

    private async Task LoadData()
    {
        // Marshall onto the dispatcher thread
        var watch = new Stopwatch("SelectedLoadData");

        gridImages.Clear();
        gridImages.AddRange(basketService.BasketImages);
        watch.Stop();

        StateHasChanged();
    }

}